/**
 * CreateTime   : 2020年8月29日
 * Des          : UI基类
 */

import { Component, Node, v3, Widget } from "cc";
import { EnUIState, EnUILayer } from "../const/EnCommon";
import { GameAPI } from "../GameAPI";
import IBaseUI from "./IBaseUI";
import { UILayerMgr } from "./UILayerMgr";
import { UISystem } from "./UISystem";

export class BaseUI extends Component implements IBaseUI
{
    // ui名字
    uiName : string;
    // ui状态
    uiState : EnUIState;
    // 是否启动UI栈
    isCtr : boolean;


    /**
     * 重写接口
     */
    public OnAwake(){}
    public OnShow(args?:any[]){}
    public Enable(){}
    public OnHide(){}
    public OnDestroy(){}
    public Disable(){}
    /**
     * 重写接口 end
     */

    onEnable()
    {
        this.Enable();
    }

    onDisable()
    {
        this.Disable();
    }
    
    onDestroy()
    {
        this.Destroy();
    }
    Awake()
    {
        this.uiName = this.node.name;
        this.uiState = EnUIState.Awke;
        this.OnAwake();
    }

    SetLayer(layer:EnUILayer)
    {
        UILayerMgr.instance.SetLayer(layer, this.node);
    }

    Show(args?:any[])
    {
        if (this.uiState == EnUIState.Show)
        {
            return;
        }
        this.node.setPosition(v3(10000, 10000, 0));
        let myThis = this;
        this.uiState = EnUIState.Show;
        this.node.active = true;
        this.scheduleOnce(function(){
            myThis.node.setPosition(v3(0, 0, 0));
            myThis.node.active = true;
        }.bind(this), 0.02);
        this.OnShow(args);
    }

    Hide()
    {
        if (this.uiState == EnUIState.Hide)
        {
            return;
        }

        this.uiState = EnUIState.Hide;
        if (this.node) {
            this.node.active = false;
            this.OnHide();
        }
    }

    Close()
    {
        if (this.isCtr)
        {
            GameAPI.ClosePanel();
        }
        else
        {
            GameAPI.ClosePanel(this.uiName);
        }
    }

    Destroy()
    {
        if (this.uiState == EnUIState.Destroy)
        {
            return;
        }

        this.uiState = EnUIState.Destroy;

        UISystem.instance.RemoveFromWhitelist(this.uiName);

        this.OnDestroy();

        // 注销所有UI全局事件
        GameAPI.OffAllCaller(this);
    }
}